package com.github.freegeese.site.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * http://jinnianshilongnian.iteye.com/blog/2040929
 */
@Slf4j
@Controller
@RequestMapping
public class LoginController {

    @RequestMapping("/login")
    public String doLogin(HttpServletRequest request, Model model) {
        String errorClassName = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        if (null != errorClassName) {
            log.info("error:{}", errorClassName);
            model.addAttribute("error", errorClassName);
        }
        return "login";
    }

    @RequiresRoles("a")
    @GetMapping("/index")
    public String toIndex() {
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.getPrincipal());
        return "index";
    }

    @RequiresRoles("b")
    @GetMapping("/test")
    public String toTest() throws Exception {
//        Subject subject = SecurityUtils.getSubject();
//        subject.checkRole("admin1");
//        subject.checkPermissions("user:create");
        return "test";
    }

    @GetMapping("/unauthorized")
    public String toUnauthorized() {
        return "unauthorized";
    }

    @GetMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/index";
    }
}
